<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElLoading, ElStatistic, ElTimeline, ElTimelineItem, ElEmpty } from 'element-plus';
import { 
  getWritingCalendar, 
  getDailyWritingDetail 
} from '@/api/detail';
import PageContainer from '@/components/PageContainer.vue';

// 响应式数据
const calendarData = ref({});
const summary = ref({});
const selectedDate = ref('');
const dailyDetail = ref(null);
const showDetailDialog = ref(false);
const currentMonth = ref(new Date().getMonth() + 1);
const currentYear = ref(new Date().getFullYear());


// 计算属性 - 生成日历网格
const calendarGrid = computed(() => {
  const grid = [];
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1);
  const lastDay = new Date(currentYear.value, currentMonth.value, 0);
  const daysInMonth = lastDay.getDate();
  
  // 添加上个月的最后几天
  const firstDayOfWeek = firstDay.getDay();
  const prevMonthLastDay = new Date(currentYear.value, currentMonth.value - 1, 0).getDate();
  
  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    grid.push({
      date: new Date(currentYear.value, currentMonth.value - 2, prevMonthLastDay - i),
      isCurrentMonth: false,
      wordCount: 0
    });
  }
  
  // 添加当前月的日期
  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(currentYear.value, currentMonth.value - 1, i);
    const dateKey = date.toISOString().split('T')[0];
    const dayData = calendarData.value[dateKey];
    
    grid.push({
      date,
      isCurrentMonth: true,
      wordCount: dayData?.wordCount || 0,
      hasData: dayData?.hasData || false
    });
  }
  
  // 添加下个月的前几天，补全网格
  const totalCells = 42; // 6行×7列
  const nextMonthDays = totalCells - grid.length;
  for (let i = 1; i <= nextMonthDays; i++) {
    grid.push({
      date: new Date(currentYear.value, currentMonth.value, i),
      isCurrentMonth: false,
      wordCount: 0
    });
  }

  // 调试：打印日历网格生成结果
  console.log('calendarGrid 生成结果:', grid);
  return grid;
});

// 月份名称
const monthNames = [
  '一月', '二月', '三月', '四月', '五月', '六月',
  '七月', '八月', '九月', '十月', '十一月', '十二月'
];

// 获取码字日历数据
const loading = ref(false); 
// TypeWriting.vue - 修复后的 fetchWritingCalendar 函数
const fetchWritingCalendar = async (year, month) => {
  loading.value = true
  console.log('开始获取码字日历数据，参数:', { year, month })
  
  try {
    // 修复：正确定义 params 变量
    const params = { 
      year: year || currentYear.value, 
      month: month || currentMonth.value 
    }
    
    console.log('API请求参数:', params)
    
    const response = await getWritingCalendar(params)
    console.log('API完整响应:', response)
    
    if (response.data.code === '0000') {
      console.log('获取数据成功:', response.data.data)
      calendarData.value = response.data.data.calendar || {}
      summary.value = response.data.data.summary || {
        totalWordCount: 0,
        totalDays: 0,
        currentStreak: 0,
        longestStreak: 0,
        avgDailyWords: 0
      }
      
      // 如果没有数据，显示提示
      if (Object.keys(calendarData.value).length === 0) {
        console.log('没有找到写作记录数据')
        ElMessage.info('当前月份暂无写作记录')
      }
    } else {
      console.error('API返回错误:', response.data.msg)
      ElMessage.error(response.data.msg || '获取码字日历数据失败')
    }
  } catch (error) {
    console.error('获取码字日历数据失败:', error)
    ElMessage.error('获取码字日历数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取每日写作详情
const fetchDailyDetail = async (date) => {
  try {
    // 调试：打印请求日期
    console.log('fetchDailyDetail 请求日期:', date);
    
    const response = await getDailyWritingDetail({ date });
    // 调试：打印接口响应
    console.log('fetchDailyDetail 接口响应:', response);
    
    if (response.code === '0000') {
      dailyDetail.value = response.data;
      showDetailDialog.value = true;
    } else {
      //ElMessage.success('获取每日写作详情成功 ');
    }
  } catch (error) {
    ElMessage.error('获取每日写作详情失败');
    // 调试：打印请求错误
    console.error('fetchDailyDetail 请求错误:', error);
  }
};

// 处理日期点击
const handleDateClick = (day) => {
  // 调试：打印点击的日期数据
  console.log('handleDateClick 点击的日期:', day);
  
  if (day.hasData) {
    const dateKey = day.date.toISOString().split('T')[0];
    selectedDate.value = dateKey;
    fetchDailyDetail(dateKey);
  }
};

// 切换月份
const changeMonth = (direction) => {
  if (direction === 'prev') {
    if (currentMonth.value === 1) {
      currentMonth.value = 12;
      currentYear.value--;
    } else {
      currentMonth.value--;
    }
  } else {
    if (currentMonth.value === 12) {
      currentMonth.value = 1;
      currentYear.value++;
    } else {
      currentMonth.value++;
    }
  }
  fetchWritingCalendar(currentYear.value, currentMonth.value);
};

// 获取字数显示颜色
const getWordCountColor = (wordCount) => {
  if (wordCount === 0) return '#ebedf0';
  if (wordCount < 1000) return '#c6e48b';
  if (wordCount < 3000) return '#7bc96f';
  if (wordCount < 6000) return '#239a3b';
  return '#196127';
};

// 获取字数显示文本
const getWordCountText = (wordCount) => {
  if (wordCount === 0) return '无记录';
  if (wordCount < 1000) return `${wordCount}字`;
  return `${(wordCount / 1000).toFixed(1)}k字`;
};

// 初始化
onMounted(() => {
  // 确保使用当前时间
  const now = new Date();
  currentYear.value = now.getFullYear();
  currentMonth.value = now.getMonth() + 1;
  fetchWritingCalendar(currentYear.value, currentMonth.value);
});
</script>

<template>
  <page-container title="码字日历">
    <div class="writing-calendar">
      <!-- 统计摘要 -->
      <el-row :gutter="20" class="summary-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.totalWordCount || 0 }}</div>
              <div class="stat-label">总字数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.totalDays || 0 }}</div>
              <div class="stat-label">写作天数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.currentStreak || 0 }}</div>
              <div class="stat-label">连续写作</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.avgDailyWords || 0 }}</div>
              <div class="stat-label">日均字数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 无数据提示 -->
    <el-empty 
      v-if="Object.keys(calendarData).length === 0 && !loading" 
      description="当前月份暂无写作记录" 
      class="empty-tip"
    />
        <!-- 日历网格区域 -->
    <div class="days-grid">
    <template v-if="calendarGrid.length > 0">
        <!-- 原有日期格子代码 -->
    </template>
    <template v-else>
        <el-empty description="暂无日历数据" />
    </template>
    </div>

      <!-- 日历控件 -->
      <el-card shadow="hover" class="calendar-card">
        <template #header>
          <div class="calendar-header">
            <el-button @click="changeMonth('prev')" icon="ArrowLeft" text>
              上个月
            </el-button>
            <span class="month-title">{{ currentYear }}年 {{ monthNames[currentMonth - 1] }}</span>
            <el-button @click="changeMonth('next')" icon="ArrowRight" text>
              下个月
            </el-button>
          </div>
        </template>

        <!-- 日历网格 -->
        <div class="calendar-grid">
          <!-- 星期标题 -->
          <div class="weekdays">
            <div class="weekday" v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">
              {{ day }}
            </div>
          </div>
          
          <!-- 日期格子 -->
          <div class="days-grid">
            <template v-if="calendarGrid.length > 0">
              <!-- 原有日期格子代码 -->
                <div
                v-for="(day, index) in calendarGrid"
                :key="index"
                class="day-cell"
                :class="{
                  'current-month': day.isCurrentMonth,
                  'has-data': day.hasData,
                  'selected': selectedDate === day.date.toISOString().split('T')[0]
                }"
                @click="handleDateClick(day)"
              >
                <div class="day-number">{{ day.date.getDate() }}</div>
                <div
                  class="word-count-indicator"
                  :style="{ backgroundColor: getWordCountColor(day.wordCount) }"
                ></div>
                <div class="word-count-text" v-if="day.hasData">
                  {{ getWordCountText(day.wordCount) }}
                </div>
                </div>
            </template>
            <template v-else-if="!loading"> <!-- 仅在加载完成后显示 -->
              <el-empty description="暂无日历数据" />
            </template>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 每日写作详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      :title="`${selectedDate} 写作详情`"
      width="600px"
    >
      <div v-if="dailyDetail" class="daily-detail">
        <div class="daily-summary">
          <el-statistic title="总字数" :value="dailyDetail.totalWordCount" />
          <el-statistic title="写作时间" :value="dailyDetail.writingTime" suffix="分钟" />
        </div>
        
        <el-divider content-position="left">章节列表</el-divider>
        
        <div class="chapters-list" v-if="dailyDetail.chapters.length > 0">
          <el-timeline>
            <el-timeline-item
              v-for="chapter in dailyDetail.chapters"
              :key="chapter.id"
              :timestamp="new Date(chapter.publishTime).toLocaleTimeString()"
            >
              <el-card>
                <h4>{{ chapter.novelTitle }} - {{ chapter.chapterTitle }}</h4>
                <p>{{ chapter.wordCount }} 字</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        
        <div v-else class="empty-chapters">
          <el-empty description="该日期没有写作记录" />
        </div>
      </div>
    </el-dialog>
  </page-container>
</template>

<style lang="scss" scoped>
.writing-calendar {
  .summary-cards {
    margin-bottom: 20px;
    
    .stat-card {
      .stat-item {
        text-align: center;
        padding: 20px 0;
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 8px;
        }
        
        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
  
  .calendar-card {
    .calendar-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .month-title {
        font-size: 18px;
        font-weight: bold;
      }
    }
    
    .calendar-grid {
      .weekdays {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        text-align: center;
        margin-bottom: 10px;
        
        .weekday {
          padding: 10px;
          font-weight: bold;
          color: #606266;
        }
      }
      
      .days-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 4px;
        
        .day-cell {
          aspect-ratio: 1;
          border: 1px solid #e4e7ed;
          border-radius: 4px;
          padding: 8px;
          cursor: pointer;
          position: relative;
          transition: all 0.3s;
          
          &:hover {
            border-color: #409eff;
            transform: scale(1.05);
          }
          
          &.current-month {
            background-color: #fafafa;
          }
          
          &.has-data {
            background-color: #f0f9ff;
          }
          
          &.selected {
            border-color: #409eff;
            background-color: #ecf5ff;
          }
          
          .day-number {
            font-size: 12px;
            color: #606266;
          }
          
          .word-count-indicator {
            position: absolute;
            top: 2px;
            right: 2px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
          }
          
          .word-count-text {
            font-size: 10px;
            color: #909399;
            margin-top: 4px;
            text-align: center;
          }
        }
      }
    }
  }
  
  .daily-detail {
    .daily-summary {
      display: flex;
      justify-content: space-around;
      margin-bottom: 20px;
    }
    
    .chapters-list {
      max-height: 400px;
      overflow-y: auto;
    }
    
    .empty-chapters {
      text-align: center;
      padding: 40px 0;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .writing-calendar {
    .summary-cards {
      .el-col {
        margin-bottom: 10px;
      }
    }
    
    .calendar-grid .days-grid .day-cell {
      padding: 4px;
      
      .word-count-text {
        font-size: 8px;
      }
    }
  }
}
</style>